package com.danciyixue.boot.dcyx.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.danciyixue.boot.core.security.util.SecurityUtils;
import com.danciyixue.boot.dcyx.model.entity.UserExtensions;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.danciyixue.boot.dcyx.mapper.UnitStudyStatusMapper;
import com.danciyixue.boot.dcyx.service.UnitStudyStatusService;
import com.danciyixue.boot.dcyx.model.entity.UnitStudyStatus;
import com.danciyixue.boot.dcyx.model.form.UnitStudyStatusForm;
import com.danciyixue.boot.dcyx.model.query.UnitStudyStatusQuery;
import com.danciyixue.boot.dcyx.model.vo.UnitStudyStatusVO;
import com.danciyixue.boot.dcyx.converter.UnitStudyStatusConverter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 用户单元学习状态服务实现类
 *
 * @author youlaitech
 * @since 2025-06-27 11:06
 */
@Service
@DS("dcyx")
@RequiredArgsConstructor
public class UnitStudyStatusServiceImpl extends ServiceImpl<UnitStudyStatusMapper, UnitStudyStatus> implements UnitStudyStatusService {

    private final UnitStudyStatusConverter unitStudyStatusConverter;

    /**
    * 获取用户单元学习状态分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<UnitStudyStatusVO>} 用户单元学习状态分页列表
    */
    @Override
    public IPage<UnitStudyStatusVO> getUnitStudyStatusPage(UnitStudyStatusQuery queryParams) {
        Page<UnitStudyStatusVO> pageVO = this.baseMapper.getUnitStudyStatusPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取用户单元学习状态表单数据
     *
     * @param id 用户单元学习状态ID
     * @return 用户单元学习状态表单数据
     */
    @Override
    public UnitStudyStatusForm getUnitStudyStatusFormData(Long id) {
        UnitStudyStatus entity = this.getById(id);
        return unitStudyStatusConverter.toForm(entity);
    }
    
    /**
     * 新增用户单元学习状态
     *
     * @param formData 用户单元学习状态表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveUnitStudyStatus(UnitStudyStatusForm formData) {
        UnitStudyStatus entity = unitStudyStatusConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新用户单元学习状态
     *
     * @param id   用户单元学习状态ID
     * @param formData 用户单元学习状态表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateUnitStudyStatus(Long id,UnitStudyStatusForm formData) {
        UnitStudyStatus entity = unitStudyStatusConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除用户单元学习状态
     *
     * @param ids 用户单元学习状态ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteUnitStudyStatuss(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的用户单元学习状态数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    @Override
    public boolean saveOrUpdateUnitStudyStatus(UnitStudyStatusForm formData) {

        Long userId = SecurityUtils.getUserId();
        formData.setUserId(userId);
        // 根据用户ID和单元ID查找现有记录
        UnitStudyStatus existingRecord = this.getOne(new LambdaQueryWrapper<UnitStudyStatus>()
                .eq(UnitStudyStatus::getUserId, userId)
                .eq(UnitStudyStatus::getUnitId, formData.getUnitId())
        );

        if (existingRecord == null) {
            UnitStudyStatus newEntity = unitStudyStatusConverter.toEntity(formData);
            return this.save(newEntity);
        } else {
//            formData.setId(existingRecord.getId());
            switch (formData.getSource()) {
                case 0:
                    existingRecord.setMemoryCompleted(formData.getMemoryCompleted());
                    existingRecord.setMemoryScore(formData.getMemoryScore());
                    existingRecord.setMemoryTimeConsuming(formData.getMemoryTimeConsuming());
                    break;
                case 1:
                    existingRecord.setDictationCompleted(formData.getDictationCompleted());
                    existingRecord.setDictationScore(formData.getDictationScore());
                    existingRecord.setDictationTimeConsuming(formData.getDictationTimeConsuming());
                    break;
                case 2:
                    existingRecord.setWritingCompleted(formData.getWritingCompleted());
                    existingRecord.setWritingScore(formData.getWritingScore());
                    existingRecord.setWritingTimeConsuming(formData.getWritingTimeConsuming());
                    break;
            }

            return this.updateById(existingRecord);
        }
    }
}
